package com.yh.crystal.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.handler.Handler;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.yh.crystal.AppInit;
import com.yh.crystal.controller.HomeController;

public class CrystalConfig extends JFinalConfig {

	private static final cn.hutool.log.Log log = cn.hutool.log.LogFactory.get();

	public static Prop g_prop = null;

	public static void main(String[] args) {
		UndertowServer.start(CrystalConfig.class);
		log.info("start");
	}

	@Override
	public void configConstant(Constants me) {
		g_prop = (null == g_prop ? PropKit.use("g.properties") : g_prop);
		me.setDevMode(g_prop.getBoolean("devMode", true));
		AppInit.init();
	}

	@Override
	public void configRoute(Routes me) {
		me.add("/", HomeController.class);
	}

	@Override
	public void configEngine(Engine me) {
		Engine.setFastMode(true);
		Engine.setChineseExpression(true);
		me.addSharedFunction("_layout.html");
		me.setDevMode(g_prop.getBoolean("devMode", true));
		me.setCompressorOn('\n');
	}

	@Override
	public void configPlugin(Plugins me) {

	}

	@Override
	public void configInterceptor(Interceptors me) {
	}

	@Override
	public void configHandler(Handlers me) {
		me.add(new ContextPathHandler("ctx"));
		me.add(new Handler() {
			@Override
			public void handle(String target, HttpServletRequest request, HttpServletResponse response,
					boolean[] isHandled) {
				g_prop.getProperties().keySet().forEach(n -> {
					request.setAttribute(n.toString(), g_prop.get(n.toString(), ""));
				});
				next.handle(target, request, response, isHandled);
			}
		});
	}

}
